-module(looplist).
-export([createLoopList/1, addPacket/3, takePacket/1, moveStart/1]).

-record(loopList, {start=0, readPos=0, recvSlots=[], total=0}).


createLoopList(0) -> 
	#loopList{total=0, recvSlots=loop(0)};
createLoopList(N) ->
	#loopList{total=N, recvSlots=loop(N)}.

addPacket(LoopList, Pack, Index) ->
	Id = (LoopList#loopList.start+Index) rem LoopList#loopList.total,
	RecvSlots = LoopList#loopList.recvSlots,
	LoopList#loopList{recvSlots=lists:sublist(RecvSlots, Id)++[Pack]++lists:nthtail(Id+1, RecvSlots)}.

takePacket(LoopList)->
	ReadPos = LoopList#loopList.readPos,
	Total = LoopList#loopList.total,

	case lists:nth(LoopList#loopList.readPos, LoopList) of
		undefined -> 
			{undefined, LoopList};
		Other -> 
			{Other, LoopList#loopList{readPos=(ReadPos+1) rem Total}}
	end.

moveStart(LoopList) -> 
	Start = LoopList#loopList.start,
	Total = LoopList#loopList.total,

	LoopList#loopList{start=(Start+1) rem Total}.



loop(0) ->
	[];
loop(N) ->
	[undefined | loop(N-1)].
	